package com.itholmes.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.itholmes.pojo.Result;
import com.itholmes.pojo.User;
import com.itholmes.service.UserSelectOneService;
import com.itholmes.utils.ServletForJsonUtil;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = ServletForJsonUtil.jsonToObj(req, User.class);
		UserSelectOneService service = new UserSelectOneService();
		Result result = service.matchUser(user);
		
		if(result.getCode() == 1) {
			
			User data = (User)result.getData();
			
			//第一种方式：使用cookie添加上面去，随后用sessionstorage进行传输。
			Cookie cookie = new Cookie("user_id", Integer.toString(data.getUser_id()));
			resp.addCookie(cookie);
			
			//第二种方式：使用token来进行判别
			
		}
		
		Gson gson = new Gson();
		String json = gson.toJson(result);
		
		resp.getWriter().write(json);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
}
